package com.solo.system.model.notice;

import com.mybatisflex.core.paginate.Page;
import com.solo.system.api.consts.notice.NoticeLevel;
import com.solo.system.api.entity.SysNotice;
import com.solo.system.model.message.MessageResp;
import com.solo.system.model.notice.req.NoticeCreateReq;
import com.solo.system.model.notice.req.NoticePublishReq;
import com.solo.system.model.notice.req.NoticeUpdateReq;
import com.solo.system.model.notice.resp.NoticeGetResp;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 通知公告实体转换类
 * @author 十一
 * @since 2024-12-02 17:27
 * 人生若只如初见，何事秋风悲画扇
 **/
@Mapper
public interface SysNoticeConvert {

    SysNoticeConvert INSTANCE = Mappers.getMapper(SysNoticeConvert.class);

    SysNotice convert(NoticeCreateReq bean);

    SysNotice convert(NoticeUpdateReq bean);
    
    SysNotice convert(NoticePublishReq bean);

    NoticeGetResp convertGet(SysNotice bean);

    @Mappings({
            @Mapping(source = "level.label", target = "extra"),
            @Mapping(source = "level", target = "tagType", qualifiedByName = "getTagType"),
            @Mapping(source = "level", target = "avatar", qualifiedByName = "getAvatar"),
            @Mapping(source = "sendTime", target = "datetime", qualifiedByName = "getDateTime"),
    })
    MessageResp convertMessage(SysNotice bean);

    Page<MessageResp> convertMessage(Page<SysNotice> list);

    @Named("getTagType")
    default String getTagType(NoticeLevel level) {
        return switch (level) {
            case URGENT -> "danger";
            case GENERAL -> "primary";
            default -> "info";
        };
    }
    
    @Named("getAvatar")
    default String getAvatar(NoticeLevel level) {
        return switch (level) {
            case URGENT -> "https://gw.alipayobjects.com/zos/rmsportal/WdGqmHpayyMjiEhcKoVE.png}";
            case GENERAL -> "primary";
            default -> "info";
        };
    }

    @Named("getDateTime")
    default String getDateTime(LocalDateTime sendTime) {
        if (sendTime == null) {
            return "很久很久以前";
        }
        Duration duration = Duration.between(sendTime, LocalDateTime.now());
        long days = duration.toDays();
        long months = days / 30;  // 简单按照每月30天估算月数
        long years = days / 365;  // 简单按照每年365天估算年数
        if (years > 0) {
            return years + "年前";
        } else if (months > 0) {
            return months + "月前";
        } else if (days > 0) {
            return days + "天前";
        } else {
            return sendTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        }
    }

}
